package com.har.modules.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.har.common.exception.RRException;
import com.har.common.utils.*;
import com.har.modules.web.dao.UserDao;
import com.har.modules.web.entity.*;
import com.har.modules.web.service.SmsService;
import com.har.modules.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
@Slf4j
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao,UserEntity> implements UserService {

    @Autowired
    private SmsService smsService;

    @Override
    public UserLoginEntity selectOne(LoginEntity loginEntity) throws Exception {
        if(StringUtil.isEmpty(loginEntity.getUsername())){
            throw new RRException("请输入用户名");
        }
        if (StringUtil.isEmpty(loginEntity.getPassword())){
            throw new RRException("请输入密码");
        }
        if(StringUtil.isEmpty(loginEntity.getCode())){
            throw  new RRException("请输入验证码");
        }
        if (!StringUtils.equalsIgnoreCase(loginEntity.getCode(), MapUtils.maps.get("nCode"))) {  //忽略验证码大小写
            throw  new RRException("图形验证码错误，请重新获取");
        }
        boolean flag=false;
        UserEntity userEntity=new UserEntity();
        if(!flag){
            EntityWrapper<UserEntity> ew=new EntityWrapper<>();
            ew.eq("password",loginEntity.getPassword());
            ew.eq("user_name",loginEntity.getUsername());
            userEntity=this.selectOne(ew);
            if(null==userEntity){
                flag=true;
            }
        }
        if (flag){
            EntityWrapper<UserEntity> ew=new EntityWrapper<>();
            ew.eq("password",loginEntity.getPassword());
            ew.eq("mobile",loginEntity.getUsername());
            userEntity=this.selectOne(ew);
            if(null==userEntity){
                flag=true;
            }else {
                flag=false;
            }
        }
        if (flag){
            EntityWrapper<UserEntity> ew=new EntityWrapper<>();
            ew.eq("password",loginEntity.getPassword());
            ew.eq("id_card",loginEntity.getUsername());
            userEntity=this.selectOne(ew);
        }
        if(null==userEntity){
            throw  new RRException("账号或密码错误，请重新输入");
        }
        log.info("login>>>type>>>{}>>>userName>>>{}>>>password>>>{}>>>>code>>>{}>>>status>>>{}",
                loginEntity.getType(),loginEntity.getUsername(), loginEntity.getPassword(),
                loginEntity.getCode(),userEntity.getStatus());
        if(0==userEntity.getStatus()){
            throw  new RRException("账号未启用，请联系客服");
        }
        MapUtils.maps.clear();
        UserLoginEntity userLoginEntity=new UserLoginEntity();
        userLoginEntity.setId(userEntity.getId());
        userLoginEntity.setUsername(userEntity.getUserName());
        userLoginEntity.setRealname(userEntity.getRealName());
        userLoginEntity.setType(0);

        JSONObject cookieJson = new JSONObject();
        cookieJson.put("id",userEntity.getId());
        cookieJson.put("mobile",userEntity.getMobile());
        cookieJson.put("loginTime",DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
        cookieJson.put("userName",userEntity.getUserName());
        //用户类型 1:企业 0:员工
        cookieJson.put("type",0);
        userLoginEntity.setToken(AESUtil.getInstance().encrypt(cookieJson.toJSONString()));
        return  userLoginEntity;
    }

    @Override
    public void update(ResetEntity resetEntity) throws ParseException {
        if(StringUtil.isEmpty(resetEntity.getUsername())){
            throw new RRException("用户名为空");
        }
        if(StringUtil.strLength(resetEntity.getUsername())>20){
            throw new RRException("用户名请输入20位以内字符");
        }
        if(!ValidatUtil.checkMobileNumber(resetEntity.getMobile())){
            throw  new RRException("请输入正确的手机号");
        }
        UserEntity userEntity=new UserEntity();
        EntityWrapper<UserEntity> ew=new EntityWrapper<>();
        Boolean b=smsService.contrastDate(resetEntity.getMobile(),resetEntity.getCode());
        if (!b){
            throw new RRException("验证码失效，请重新获取验证码");
        }

        if(StringUtil.isEmpty(resetEntity.getPassword())){
            throw new RRException("密码为空");
        }
        if(StringUtil.isEmpty(resetEntity.getMobile())){
            throw new RRException("手机号为空");
        }
        if(!StringUtil.isEmpty(resetEntity.getMobile())){
            ew.eq("user_name",resetEntity.getUsername());
            ew.eq("mobile",resetEntity.getMobile());
            userEntity=this.selectOne(ew);
            if(null==userEntity){
                throw  new RRException("员工账号不存在，请先注册或联系客服");
            }
            if (!StringUtil.isEmpty(resetEntity.getPassword())){
                userEntity.setPassword(resetEntity.getPassword());
            }
        }
        updateById(userEntity);
    }

    @Override
    public UserEntity updateOfBack(UserOrCompanyEntity user) throws ParseException {
        EntityWrapper<UserEntity> ew=new EntityWrapper<>();
        UserEntity userEntity=new UserEntity();
        if(!StringUtil.isEmpty(user.getId().toString())){
            userEntity.setId(user.getId());
        }
        userEntity=this.selectOne(ew.eq("id",user.getId()));
        //当新旧密码不为空修改密码
        if(!StringUtil.isEmpty(user.getNewPassword())&&!StringUtil.isEmpty(user.getOldPassword())){
            if(null!=user.getId()&&!StringUtil.isEmpty(user.getOldPassword())){
                ew.eq("id",user.getId())
                        .eq("password",user.getOldPassword());
                UserEntity userEntity1=this.selectOne(ew);
                if(null==userEntity1){
                    throw  new RRException("原密码错误，请重新输入");
                }
                //设置为新密码
                userEntity.setPassword(user.getNewPassword());
            }

        }
        //当真实姓名不为空
        if(!StringUtil.isEmpty(user.getRealname())){
            userEntity.setRealName(user.getRealname());
        }
        //当身份证号不为空
        if(!StringUtil.isEmpty(user.getIdCard())){
            userEntity.setIdCard(user.getIdCard());
        }
        //就职企业
        if(!StringUtil.isEmpty(user.getCompanyName())){
            userEntity.setCompanyName(user.getCompanyName());
        }
        //修改手机号  验证当前手机号和验证码
        if(!StringUtil.isEmpty(user.getNewCode())&&!StringUtil.isEmpty(user.getOldCode())){
            //通过验证码和手机号进行验证原手机
            Boolean b=smsService.contrastDate(user.getOldMobile(),user.getOldCode());
            if (!b){
                throw new RRException("原手机验证码失效，请重新获取验证码");
            }
            //通过验证码和手机号进行验证当前手机
            Boolean b1=smsService.contrastDate(user.getNewMobile(),user.getNewCode());
            if (!b1){
                throw new RRException("新手机验证码失效，请重新获取验证码");
            }
            userEntity.setMobile(user.getNewMobile());
        }
        //解除微信昵称和openid
        if(!StringUtil.isEmpty(user.getUntieCode())&&!StringUtil.isEmpty(user.getMobile())){
            //通过验证码和手机号进行验证当前手机
            Boolean b=smsService.contrastDate(user.getMobile(),user.getUntieCode());
            if (!b){
                throw new RRException("手机验证码失效，请重新获取验证码");
            }
            userEntity.setOpenId(null);
            userEntity.setNickName(null);
        }
        userEntity.setUpdateTime(new Date());
        updateAllColumnById(userEntity);
        return userEntity;
    }

    @Override
    public UserBackEntity selectById(Long id) {
        if(StringUtil.isEmpty(String.valueOf(id))){
            throw new RRException("id为空，查询失败");
        }
        UserBackEntity user=new UserBackEntity();
        EntityWrapper<UserEntity> ew=new EntityWrapper<>();
        //只查询启用的用户
        ew.eq("status",1);
        ew.eq("id",id);
        log.info("id>>>{}",id);
        UserEntity userEntity=this.selectOne(ew);
        log.info("user>>>{}",userEntity);
        if(null!=userEntity){
            user.setId(userEntity.getId());
            user.setUserName(userEntity.getUserName());
            user.setRealName(userEntity.getRealName());
            user.setMobile(userEntity.getMobile());
            user.setIdCard(userEntity.getIdCard());
            user.setNickName(userEntity.getNickName());
            if(null!=userEntity.getCompanyName()){
                user.setCompanyName(userEntity.getCompanyName());
            }
        }
        return user;
    }

    @Override
    public UCBackEntity queryUser(Long id, String mobile) {
        UCBackEntity ucBackEntity=new UCBackEntity();
        EntityWrapper<UserEntity> ew=new EntityWrapper<>();
        if(!StringUtil.isEmpty(String.valueOf(id))&&!StringUtil.isEmpty(mobile)){
            ew.eq("id",id);
            ew.eq("mobile",mobile);
        }else {
            throw new RRException("id或手机号为空");
        }
        UserEntity userEntity=this.selectOne(ew);
        ucBackEntity.setCompanyName(userEntity.getCompanyName());
        ucBackEntity.setRealname(userEntity.getRealName());
        ucBackEntity.setMobile(userEntity.getMobile());

        return ucBackEntity;
    }

    @Override
    public void updateNickName(JSONObject dataJson) {
        //获取微信返回的用户信息
        String userinfo=dataJson.getString("userinfo");
        //用户类型加id
        String state=dataJson.getString("state");
        JSONObject data= (JSONObject) JSONObject.parse(userinfo);
        //微信用户昵称
        String nickName=data.getString("nickname");
        //微信openid
        String openId=data.getString("openid");
        //截取用户id
        Long userId=Long.valueOf(state.substring(1));
        log.info("userId>>>{}",userId);
        UserEntity userEntity=new UserEntity();
        userEntity.setId(userId);
        userEntity.setOpenId(openId);
        userEntity.setNickName(nickName);
        updateById(userEntity);
    }

    @Override
    public UserEntity queryNickName(Long id) {
        EntityWrapper<UserEntity> ew=new EntityWrapper<>();
        ew.eq("id",id);
        UserEntity userEntity=this.selectOne(ew);
        userEntity.setUpdateTime(null);
        userEntity.setOpenId(null);
        userEntity.setPassword(null);
        userEntity.setIdCard(null);
        userEntity.setRealName(null);
        userEntity.setCompanyName(null);
        userEntity.setStatus(null);
        userEntity.setCreateTime(null);
        userEntity.setMobile(null);
        userEntity.setUserName(null);
        return userEntity;
    }
}
